/*
 * @Author: xiaosihan
 * @Date: 2024-10-02 14:09:50
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-10-03 17:56:17
 */

import isString from 'lodash/isString';
import isObject from 'lodash/isObject';
import { clone } from 'ramda';
import { GoodsData } from '#/type';

class GoodsUtils {
  keys: Array<keyof GoodsData> = [
    'colors',
    'component',
    'mockupUrls',
    'size',
    'sizeInfo',
    'thumbs',
    'sizePrice',
  ];
  //将 商品数据中的 json 字符串转成json格式
  tojson(goodsData: GoodsData) {
    const newGoodsData = clone(goodsData);
    this.keys.map((key) => {
      let value = {};
      do {
        value = newGoodsData[key];
        if (isString(value)) {
          newGoodsData[key] = JSON.parse(value as string) as never;
        }
      } while (isString(value));
    });
    return newGoodsData;
  }

  //将 商品数据中的 json 转成json字符串
  toString(goodsData: GoodsData) {
    const newGoodsData = clone(goodsData);
    this.keys.map((key) => {
      const value = newGoodsData[key];
      if (isObject(value)) {
        newGoodsData[key] = JSON.stringify(value) as never;
      }
    });
    return newGoodsData;
  }
}

const goodsUtils = new GoodsUtils();

export default goodsUtils;
